package com.cn.ant.modules.wechat.service;

import com.cn.ant.common.persistence.Page;
import com.cn.ant.common.service.BaseService;
import com.cn.ant.common.utils.HttpClientConnectionManager;
import com.cn.ant.common.utils.HttpClientUtils;
import com.cn.ant.common.utils.Identities;
import com.cn.ant.modules.wechat.dao.AccessTokenYwMapper;
import com.cn.ant.modules.wechat.dao.MenuEntityMapper;
import com.cn.ant.modules.wechat.entity.MenuEntity;
import com.cn.ant.modules.wechat.entity.WeixinAccount;
import com.cn.ant.modules.wechat.utils.AccessToken;
import com.cn.ant.modules.wechat.utils.WeiXinConstants;
import com.cn.ant.modules.wechat.utils.WeixinUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 菜单对象Service
 * @author AntDream
 * @version 2015-03-23
 */
@Component
@Transactional(readOnly = true)
public class MenuEntityService extends BaseService {

	@Autowired
	private MenuEntityMapper menuEntityMapper;
    @Autowired
    private WeixinAccountServiceImpl accountService;
    @Autowired
    private AccessTokenYwMapper tokenYwMapper;
	
	public MenuEntity get(String id) {
		return menuEntityMapper.get(id);
	}
	
	public Page<MenuEntity> find(Page<MenuEntity> page, Map<String,Object> param) {
        page.setList(menuEntityMapper.query(param));
        page.setCount(100);
        return page;
	}

    public List<MenuEntity> queryForList(Map<String,Object> param) {
        return menuEntityMapper.query(param);
    }

    public MenuEntity findByMenuKey(String menuKey) {
        return menuEntityMapper.findByMenuKey(menuKey);
    }

    @Transactional(readOnly = false)
	public void save(MenuEntity menuEntity) {
		menuEntityMapper.insert(menuEntity);
	}
	
	@Transactional(readOnly = false)
	public void update(MenuEntity menuEntity) {
		menuEntityMapper.update(menuEntity);
	}
	
	@Transactional(readOnly = false)
	public void delete(String id) {
		menuEntityMapper.delete(id);
	}

    /**
     * 同步微信菜单
     * @param account
     * @return
     */
    @Transactional(readOnly = false)
    public Map<String, String> syncMenu(WeixinAccount account) {
        Map<String, String> retMap = new HashMap<>();
        AccessToken token = WeixinUtil.getAccessToken(accountService, account.getAccountAppId(), account.getAccountAppSecret());
        try {
            if (token == null) {
                retMap.put("ec", "error");
                retMap.put("em", "token为空");
            } else {
                String url = WeiXinConstants.WX_MENU_GET;
                Map<String, String> params = new HashMap<>();
                params.put("access_token", token.getToken());
                JSONObject jo = HttpClientUtils.getByJson(url, params);
                if (jo.has("errcode")) {
                    retMap.put("ec", "error");
                    retMap.put("em", jo.getString("errmsg"));
                    logger.debug("请求出现异常,响应报文为:" + jo.toString());
                } else {
                    //解析响应报文
                    JSONObject menuJo = jo.getJSONObject("menu");
                    if (menuJo != null) {
                        List<MenuEntity> menuList = new ArrayList<>();
                        JSONArray ja = menuJo.getJSONArray("button");
                        for (int i = 0; i < ja.size(); i++) {
                            JSONObject tempJo = ja.getJSONObject(i);
                            String type = tempJo.has("type") ? tempJo.getString("type") : "";
                            String name = tempJo.has("name") ? tempJo.getString("name") : "";
                            String key = tempJo.has("key") ? tempJo.getString("key") : "";
                            String murl = "";
                            if ("view".equals(type)) {
                                murl = tempJo.has("url") ? tempJo.getString("url") : "";
                            }
                            MenuEntity menu = new MenuEntity(Identities.generateUUID(),key, "text", name, String.valueOf(i), type, murl, "1", account.getId());
                            menuList.add(menu);
                            JSONArray subButtonJa = tempJo.getJSONArray("sub_button");
                            //判断是否有二级菜单
                            if (subButtonJa != null && subButtonJa.size() > 0) {
                                for (int j = 0; j < subButtonJa.size(); j++) {
                                    JSONObject subJo = subButtonJa.getJSONObject(j);
                                    String subtype = subJo.has("type") ? subJo.getString("type") : "";
                                    String subname = subJo.has("name") ? subJo.getString("name") : "";
                                    String subkey = subJo.getString("key");
                                    String surl = "";
                                    if ("view".equals(subtype)) {
                                        surl = subJo.has("url") ? subJo.getString("url") : "";
                                    }
                                    MenuEntity submenu = new MenuEntity(Identities.generateUUID(), subkey, "text", subname, String.valueOf(i), subtype, surl, menu.getId(), account.getId());
                                    menuList.add(submenu);
                                }
                            }
                        }
                        //将现有的菜单先删除掉
                        menuEntityMapper.deleteByAccountId(account.getId());
                        //添加菜单
                        int num = menuEntityMapper.batchInsert(menuList);
                    }
                }
                retMap.put("ec", "success");
                retMap.put("em", "菜单同步成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            retMap.put("ec", "error");
            retMap.put("em", e.getMessage());
        }
        return retMap;
    }

    /**
     * 提交微信菜单,将修改微信的菜单
     * @param accountId
     * @return
     */
    @Transactional(readOnly = false)
    public Map<String, String> uploadMenu(String accountId) {
        Map<String, String> retMap = new HashMap<>();
        List<MenuEntity> menuEntityList = menuEntityMapper.queryByAccountId(accountId);
        JSONObject root = new JSONObject();
        JSONArray btnJa = new JSONArray();
        for (int i = 0; i < menuEntityList.size(); i++) {
            MenuEntity tempMenu = menuEntityList.get(i);
            if (tempMenu.getFatherid().equals("1")) {
                JSONObject fjo = new JSONObject();
                fjo.put("name", tempMenu.getName());
                if (tempMenu.getChildList() == null || tempMenu.getChildList().size() == 0) {
                    //没有下级菜单
                    fjo.put("type", tempMenu.getType());
                    fjo.put("key", tempMenu.getMenukey());
                    if ("view".equals(tempMenu.getType())) {
                        fjo.put("url", tempMenu.getUrl());
                    }
                } else {
                    //有下级菜单
                    JSONArray subJa = new JSONArray();
                    for (MenuEntity menuEntity : tempMenu.getChildList()) {
                        JSONObject subjo = new JSONObject();
                        subjo.put("type", menuEntity.getType());
                        subjo.put("name", menuEntity.getName());
                        subjo.put("key", menuEntity.getMenukey());
                        if ("view".equals(menuEntity.getType())) {
                            subjo.put("url", menuEntity.getUrl());
                        }
                        subJa.add(subjo);
                    }
                    fjo.put("sub_button", subJa);
                }
                btnJa.add(fjo);
            } else {
                continue;
            }
        }
        root.put("button", btnJa);
        String body = root.toString();//上传数据
        WeixinAccount account = accountService.get(accountId);
        AccessToken token = WeixinUtil.getAccessToken(accountService, account.getAccountAppId(), account.getAccountAppSecret());
        logger.debug("创建自定义菜单的access_token:" + token.getToken());
        logger.debug("创建自定义菜单的body报文:" + body);
        HttpPost httpost = HttpClientConnectionManager.getPostMethod(WeiXinConstants.WX_MENU_CREATE + "?access_token=" + token.getToken());
        httpost.setEntity(new StringEntity(body, "UTF-8"));
        HttpClient httpClient = HttpClientConnectionManager.getHttpClient();
        JSONObject result = null;
        try {
            HttpResponse response = httpClient.execute(httpost);
            String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
            result = JSONObject.fromObject(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.debug("响应信息为:" + result.toString());
        if (result != null) {
            if (result.getString("errcode").equals("0")) {
                retMap.put("ec", "success");
                retMap.put("em", "创建菜单成功");
            } else {
                retMap.put("ec", result.getString("errcode"));
                retMap.put("em", result.getString("errmsg"));
            }
        } else {
            retMap.put("ec", "error");
            retMap.put("em", "创建菜单失败");
        }
        return retMap;
    }

}
